import React, { useState,useEffect } from 'react';
import { LockOutlined,MobileOutlined,SafetyOutlined } from '@ant-design/icons';
import { Button, Form, Input } from 'antd';
import { useHistory } from 'react-router-dom';
import backgroundImage from '../assets/images/1.jpg';
import axios from 'axios';
import { Carousel } from 'react-responsive-carousel';
import logo1 from '../assets/images/2.jpg';
import logo2 from '../assets/images/3.jpg';
import logo3 from '../assets/images/4.jpg';
import logo4 from '../assets/images/5.jpg';
import logo5 from '../assets/images/6.jpg';
import logo6 from '../assets/images/7.jpg';

const Password = () => {

  //使用useState定义一个名为formValid的state变量，并将初始值设为false
  const [formValid, setFormValid] = useState(false);
  const [form] = Form.useForm();
  const [passwd,setPasswd] = useState('');
  const [phone,setPhone] = useState('');
  const [verifyMsg,setverifyMsg] = useState('');
  const [countdown, setCountdown] = useState(0);

  // 点击发送手机验证码按钮，发送验证码
  const submitClick = () =>{
    axios.post('http://localhost:2023/auth/verifyMsg', {
      tel_number:phone,
      })
      .then((res) => {
        console.log(res);
      })
      .catch((error) => {
        console.log(error);
      });
      // // 验证手机号码格式
      if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(phone)) {
        return;
      }
      setCountdown(60);
  }
  //定义phone的数值进行输入判断，并提醒手机号是否正确，rule不可删除  
  const validatePhoneNumber = (rule, value) => {
    return new Promise((resolve, reject) => {
      if (!value) {
        reject('请输入手机号!');
      } else if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        reject('手机号格式不正确!');
      } else {
        resolve();
      }
    });
  };  
  // 定义验证码，提示输入验证码，rule不可删除
  const validateCaptcha = (rule, value) => {
    return new Promise((resolve, reject) => {
      if (!value) {
        reject('请输入验证码!');
      } else {
        resolve();
      }
    });
  };
  // 定义一个禁用的按钮，手机号未输入不能点击发送验证码
  const disableButton = !phone || countdown > 0;
  // 设置定时器，进行倒计时显示
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

  // 轮播图
  const [currentSlide, setCurrentSlide] = useState(0);
  // 增加或减少当前幻灯片的函数
  const nextSlide = () => {
    setCurrentSlide((prevSlide) => (prevSlide === totalSlides - 1 ? 0 : prevSlide + 1));
  };
  const prevSlide = () => {
    setCurrentSlide((prevSlide) => (prevSlide === 0 ? totalSlides - 1 : prevSlide - 1));
  };
  const totalSlides = 6; // 假设有6张图片
  useEffect(() => {
    const interval = setInterval(() => {
      nextSlide();
    }, 2500);
    return () => {
      clearInterval(interval);
    };
  }, [currentSlide]);

  //写入新密码
  const onFinish = () => {
    setFormValid(true);
    axios.put('http://localhost:2023/auth/repwd', {
      phone:phone, 
      passwd:passwd, 
      verifyMsg:verifyMsg,  //手机号验证码
    })
    .then((res) => {
      console.log(res.data);
      history.push('/Login');
    })
    .catch((error) => {
      console.log(error);
    });
  };
  //定义history，onClick1，通过点击事件跳转到登录页面
  const history = useHistory();
  const onClick1 = () => {
    form.validateFields().then(() => {
      if (formValid) {
        console.log('Password successful');
        // 点击确定跳转到登录页面
        //history.push("/login");
      }
    });  
};
  return (
  <div style={{ 
    display: 'flex', 
    justifyContent: 'center', 
    height: '97vh', 
    alignItems: 'center',
    backgroundImage: `url(${backgroundImage})`,//背景图
    backgroundSize: 'cover', 
  }}
  >
    {/* 轮播图 */}
    <div style={{ position: 'relative', maxWidth: '600px', margin: '0 auto',marginLeft:250 }}>
      <Carousel
      selectedItem={currentSlide}
      onChange={(index) => setCurrentSlide(index)}
      showThumbs={false}
      autoPlay={false}
      infiniteLoop={true}
      showArrows={false}
      showStatus={false}
      showIndicators={false}
      >
        <img src={logo1} alt="Image 1" style={{ width: 650, height: 408, borderRadius: '10px 0 0 10px' }} />
        <img src={logo2} alt="Image 2" style={{ width: 650, height: 408, borderRadius: '10px 0 0 10px' }} />
        <img src={logo3} alt="Image 3" style={{ width: 650, height: 408, borderRadius: '10px 0 0 10px' }} />
        <img src={logo4} alt="Image 4" style={{ width: 650, height: 408, borderRadius: '10px 0 0 10px' }} />
        <img src={logo5} alt="Image 5" style={{ width: 650, height: 408, borderRadius: '10px 0 0 10px' }} />
        <img src={logo6} alt="Image 6" style={{ width: 650, height: 408, borderRadius: '10px 0 0 10px' }} />
      </Carousel>
      <div style={{ position: 'absolute', top: '50%', transform: 'translateY(-50%)', left: -15 }}>
        <Button onClick={prevSlide} type="link" style={{color: '#55CA92',fontSize:30}}>{"<"}</Button>
      </div>
      <div style={{ position: 'absolute', top: '50%', transform: 'translateY(-50%)', right: -15}}>
        <Button onClick={nextSlide} type="link" style={{color: '#55CA92',fontSize:30}}>{">"}</Button>
      </div>
    </div>
    {/* 表单 */}
    <div 
    style={{ 
      border: '1px solid #BEBEBE',
      width: 300,
      padding: 20,
      borderRadius:'0 10px 10px 0',
      boxShadow: '0 2px 4px rgba(0, 0, 0, 0.5)',
      marginRight:260,
      }}
    >
      {/* 找回密码标题 */}
      <h1 style={{ textAlign: 'center' }}>找回密码</h1>
      <Form
      name="normal_password"
      className="password-form"
      initialValues={{remember: true}}
      onFinish={onFinish}
      >
        {/* 手机号 */}
        <Form.Item
        name="phone"
        rules={[
          {
            required: true,
            validator: validatePhoneNumber,
          }
        ]}
        value={phone}
        onChange = {(e) => setPhone(e.target.value)}
        >
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <MobileOutlined className="icon" style={{ color: '#55CA92' }} />
            <Input 
            placeholder="手机号" 
            className="input" 
            style={{ 
              width: 250, 
              marginLeft: 20,
              backgroundColor: 'rgba(255, 255, 255, 0.3)' 
            }} 
            />
          </div>
        </Form.Item>
        {/* 验证码 */}
        <Form.Item
        name="captcha"
        rules={[
          {
            required: true,
            validator: validateCaptcha,
          }
        ]}
        value={verifyMsg}
        onChange = {(e) => setverifyMsg(e.target.value)}
        >
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <SafetyOutlined className="icon" style={{ color: '#55CA92' }} />
            <Input 
            type="text" 
            placeholder="验证码" 
            className="input" 
            style={{ 
              width: 150, 
              marginLeft: 20,
              backgroundColor: 'rgba(255, 255, 255, 0.3)' 
            }} 
            />
            {/* 发送验证码按钮 */}
            <Button 
            style={{
              borderRadius:7,
              color:'white',
              backgroundColor:'#55CA92'
            }}
            onClick={submitClick}
            disabled={disableButton}
            >
              {countdown > 0 ? `${countdown}秒后重发` : '发送验证码'}
            </Button>
          </div>
        </Form.Item>
        {/* 新密码 */}
        <Form.Item 
        name="password"
        rules={[
          {
            required: true,
            message: '请输入新密码!',
          }
        ]}
        value={passwd}
        onChange = {(e) => setPasswd(e.target.value)}
        >
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <LockOutlined className="icon" style={{ color: '#55CA92' }} />
            <Input 
            type="password" 
            placeholder="新密码" 
            className="input" 
            style={{ 
              width: 250, 
              marginLeft: 20,
              backgroundColor: 'rgba(255, 255, 255, 0.3)' 
            }} 
            />
          </div>
        </Form.Item>
        {/* 再次输入，密码 */}
        <Form.Item 
        name="confirmPassword"
        dependencies={['password']}
        rules={[
          {
            required: true,
            message: '请再次输入密码!',
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
                return Promise.reject(new Error('密码输入不一致!'));
              },
            }),
          ]}
        value={passwd}
        onChange = {(e) => setPasswd(e.target.value)}
        >
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <LockOutlined className="icon" style={{ color: '#55CA92' }} />
            <Input 
            type="password"
            placeholder="再次输入密码" 
            className="input"
            style={{ 
              width: 250, 
              marginLeft: 20,
              backgroundColor: 'rgba(255, 255, 255, 0.3)' 
            }} 
            />
          </div>
        </Form.Item>
        {/* 确定按钮 */}
        <Form.Item>
          <div 
          className="button-container" 
          style={{ 
            display: 'flex', 
            justifyContent: 'center' 
          }}
          >
            <Button 
            type="text" 
            htmlType="submit" 
            className="login-form-button" 
            style={{ 
              width: 200, 
              backgroundColor: '#55CA92', 
              color: 'white', 
              textAlign: 'center',
            }}
            onClick={onClick1}
            >
              确定
            </Button>
          </div>
        </Form.Item>
      </Form>
    </div>
  </div>
  );
};

export default Password;